<?php
// +----------------------------------------------------------------------
// | Workman and Gateway-worker
// +----------------------------------------------------------------------
// | Copyright (c) 2015-2025 http://www.yicmf.com, All rights reserved.
// +----------------------------------------------------------------------
// | Author: 微尘 <yicmf@qq.com>
// +----------------------------------------------------------------------

namespace yicmf\worker\handler;


use think\facade\Log;
use Workerman\Timer;
use yicmf\worker\Server as ServerWorker;
use Workerman\Connection\TcpConnection;

class Server extends ServerWorker
{
    // 心跳时间
    protected int $hear_beat_time = 30;
    protected $port = 2345;
    protected $host = '0.0.0.0';
    protected $protocol = 'websocket';

//		protected $context  = [
//			'ssl' => [
//				// 请使用绝对路径
//				'local_cert'        => '/www/server/panel/vhost/ssl/kf.motonoaji.com/fullchain.pem', // 也可以是crt文件
//				'local_pk'          => '/www/server/panel/vhost/ssl/kf.motonoaji.com/privkey.pem',
//				'verify_peer'       => false,
//				'allow_self_signed' => false, //如果是自签名证书需要开启此选项
//			]
//		];
//
//		protected $port = 30031;
//		protected $option   = [
//			'transport'=>'ssl'
//		];


    protected function init()
    {
//        $log = config('log');
//        $log['default'] = 'socket';
//        config($log, 'log');
    }

    /**
     * 每个进程启动
     * @param $worker
     */
    public function onWorkerStart($worker)
    {

        // 1秒一次轮询
        Timer::add(1, function () use ($worker) {

        });
        // 10秒一次轮询
        Timer::add(10, function () use ($worker) {
//            $event = new ChatEvent();

        });
    }


    /**
     * 设备连接成功
     * @param TcpConnection $connection
     * @return mixed
     */
    public function onConnect(TcpConnection $connection)
    {
        $connection->connection_time = time();
        return $this->_send('Connection Success!', $connection, 'init');
    }

    /**
     * 收到消息
     * @param TcpConnection $connection
     * @param string $parameter
     * @return mixed
     */
    public function onMessage(TcpConnection $connection, string $parameter)
    {

    }

    protected function _log($data, $data_type = 'message', $type = 'info')
    {
//        Log::record($data.$type);
        $data_type != 'ping' && Log::write($data.$type) ;
    }


    public function onWorkerReload($worker)
    {
        // 重启服务
    }

    /**
     * 断开设备
     * @param TcpConnection $connection
     */
    public function onClose($connection)
    {
        echo 'close ' ."\r\n";
//        $connection->close();

    }

    public function onError($connection, $code, $msg)
    {
//        Log::channel('socket')->error('msg ' . $msg . ' error ' . $code);
    }

    /**
     * 发送指定格式数据
     * @param               $data
     * @param TcpConnection $connection
     * @param               $type
     * @param               $trace
     * @return mixed
     * @author 微尘 <yicmf@qq.com>
     */
    private function _send($data, $connection, $type, $trace = [])
    {
        $_data = [
            'cid' => $connection->id,
            'type' => $type,
            'data' => $data,
            'trace' => $trace
        ];
        //  $type = $request->get('type');
        //        $token = $request->get('token');
        //        $app = $request->get('app', 0);
        $this->_log('send ' . json_encode($_data), $type);
        return $connection->send(json_encode($_data));
    }

    private function dataCheck($data): bool
    {
        json_decode($data);
        return (json_last_error() == JSON_ERROR_NONE) && !is_numeric($data);
    }
}